package com.edgegateway.web.controller.iot;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

import com.edgegateway.common.pk.IdWorker;
import com.edgegateway.common.utils.StringUtils;
import com.edgegateway.common.utils.TelnetUtil;
import com.edgegateway.system.service.IIotRuleFlowService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edgegateway.common.annotation.Log;
import com.edgegateway.common.enums.BusinessType;
import com.edgegateway.system.domain.IotEdgeGateway;
import com.edgegateway.system.service.IIotEdgeGatewayService;
import com.edgegateway.common.core.controller.BaseController;
import com.edgegateway.common.core.domain.AjaxResult;
import com.edgegateway.common.utils.poi.ExcelUtil;
import com.edgegateway.common.core.page.TableDataInfo;

/**
 * 边缘网关Controller
 * 
 * @author ruoyi
 * @date 2023-01-03
 */
@Api("边缘网关")
@Controller
@RequestMapping("/system/gateway")
@Slf4j
public class IotEdgeGatewayController extends BaseController
{
    private String prefix = "iot/gateway";

    @Autowired
    private IIotEdgeGatewayService iotEdgeGatewayService;

    @Autowired
    private IdWorker idWorker;

    @RequiresPermissions("system:gateway:view")
    @GetMapping()
    public String gateway()
    {
        return prefix + "/gateway";
    }

    /**
     * 查询边缘网关列表
     */
    @RequiresPermissions("system:gateway:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(IotEdgeGateway iotEdgeGateway)
    {
        startPage();
        List<IotEdgeGateway> list = iotEdgeGatewayService.selectIotEdgeGatewayList(iotEdgeGateway);
        for (IotEdgeGateway edgeGateway: list){
            boolean telnet = ckeckUrl(edgeGateway.getGatewayUrl());
            if(telnet && edgeGateway.getStatus() != 1){
                edgeGateway.setStatus(1);
                iotEdgeGatewayService.updateIotEdgeGateway(edgeGateway);
            }
            if(!telnet && edgeGateway.getStatus() == 1) {
                edgeGateway.setStatus(0);
                iotEdgeGatewayService.updateIotEdgeGateway(edgeGateway);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出边缘网关列表
     */
    @RequiresPermissions("system:gateway:export")
    @Log(title = "边缘网关", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(IotEdgeGateway iotEdgeGateway)
    {
        List<IotEdgeGateway> list = iotEdgeGatewayService.selectIotEdgeGatewayList(iotEdgeGateway);
        ExcelUtil<IotEdgeGateway> util = new ExcelUtil<IotEdgeGateway>(IotEdgeGateway.class);
        return util.exportExcel(list, "边缘网关数据");
    }

    /**
     * 新增边缘网关
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存边缘网关
     */
    @RequiresPermissions("system:gateway:add")
    @Log(title = "边缘网关", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(IotEdgeGateway iotEdgeGateway)
    {
        iotEdgeGateway.setId(idWorker.nextId());
        boolean telnet = ckeckUrl(iotEdgeGateway.getGatewayUrl());
        if(telnet){
            iotEdgeGateway.setStatus(1);
        }
        return toAjax(iotEdgeGatewayService.insertIotEdgeGateway(iotEdgeGateway));
    }

    /**
     * 修改边缘网关
     */
    @RequiresPermissions("system:gateway:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        IotEdgeGateway iotEdgeGateway = iotEdgeGatewayService.selectIotEdgeGatewayById(id);
        mmap.put("iotEdgeGateway", iotEdgeGateway);
        return prefix + "/edit";
    }

    /**
     * 修改保存边缘网关
     */
    @RequiresPermissions("system:gateway:edit")
    @Log(title = "边缘网关", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(IotEdgeGateway iotEdgeGateway)
    {
        return toAjax(iotEdgeGatewayService.updateIotEdgeGateway(iotEdgeGateway));
    }

    /**
     * 删除边缘网关
     */
    @RequiresPermissions("system:gateway:remove")
    @Log(title = "边缘网关", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids){
        return toAjax(iotEdgeGatewayService.deleteIotEdgeGatewayByIds(ids));
    }

    @GetMapping("/all")
    @ResponseBody
    public AjaxResult getAll(){
        List<IotEdgeGateway> list = iotEdgeGatewayService.getAll();
        return AjaxResult.success(list);
    }

    /**
     * 判断地址是否可用
     * @param gatewayUrl
     * @return
     */
    public boolean telnet(String gatewayUrl){
        boolean b = false;
        if(StringUtils.isNotBlank(gatewayUrl)){
            try{
                URL url = new URL(gatewayUrl);
                String host = url.getHost();
                int port = url.getPort();
                if(port==-1){
                    port = url.getDefaultPort();
                }
                boolean telnet = TelnetUtil.telnet(host,port,200);
                if(telnet){
                    b=true;
                }
            }catch (MalformedURLException e){
                log.error("地址错误=>"+gatewayUrl);
            }
        }
        return b;
    }

    /**
     * 判断接口是否可用
     * @param gatewayUrl
     * @return
     */
    public boolean ckeckUrl(String gatewayUrl){
        boolean b = false;
        if(StringUtils.isNotBlank(gatewayUrl)){
            boolean telnet = TelnetUtil.checkUrl(gatewayUrl+"/diagnostics");
            if(telnet){
                b=true;
            }
        }
        return b;
    }


}
